package com.fqy.ticket.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjUtil;
import com.fqy.ticket.common.req.MemberTicketReq;
import com.fqy.ticket.common.resp.PageResp;
import com.fqy.ticket.common.util.SnowUtil;
import com.fqy.ticket.member.domain.Ticket;
import com.fqy.ticket.member.domain.TicketExample;
import com.fqy.ticket.member.mapper.TicketMapper;
import com.fqy.ticket.member.req.TicketQueryReq;
import com.fqy.ticket.member.resp.TicketQueryResp;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TicketService {

    private static final Logger LOG = LoggerFactory.getLogger(TicketService.class);

    @Resource
    private TicketMapper ticketMapper;

    /**
     * 保存Ticket记录（新增或更新）
     * @param req 保存请求对象
     */
    public void save(MemberTicketReq req) throws Exception {
        // 这个修改我提交时间好像提交早了。不知道提交到哪了，多加这一句为了跟一批操作同步
        // LOG.info("seata全局事务ID save: {}", RootContext.getXID());
        DateTime now = DateTime.now();
        Ticket ticket = BeanUtil.copyProperties(req, Ticket.class);
        ticket.setId(SnowUtil.getSnowflakeNextId());
        ticket.setCreateTime(now);
        ticket.setUpdateTime(now);
        ticketMapper.insert(ticket);
        // 模拟被调用方出现异常
        // if (1 == 1) {
        //     throw new Exception("测试异常11");
        // }
    }

    /**
     * 分页查询Ticket列表
     * @param req 查询请求对象（包含分页信息）
     * @return 分页结果
     */
    public PageResp<TicketQueryResp> queryList(TicketQueryReq req) {
        TicketExample ticketExample = new TicketExample();
        ticketExample.setOrderByClause("id desc");
        TicketExample.Criteria criteria = ticketExample.createCriteria();

        // controller已经设置会员id为当前线程id
        if (ObjUtil.isNotNull(req.getMemberId())) {
            criteria.andMemberIdEqualTo(req.getMemberId());
        }

        LOG.info("查询Ticket列表，页码：{}，每页条数：{}", req.getPage(), req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ticket> ticketList = ticketMapper.selectByExample(ticketExample);

        PageInfo<Ticket> pageInfo = new PageInfo<>(ticketList);
        LOG.info("查询结果：总行数={}，总页数={}", pageInfo.getTotal(), pageInfo.getPages());

        List<TicketQueryResp> list = BeanUtil.copyToList(ticketList, TicketQueryResp.class);

        PageResp<TicketQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    /**
     * 根据ID删除Ticket记录
     * @param id 记录ID
     */
    public void delete(Long id) {
        int count = ticketMapper.deleteByPrimaryKey(id);
    }
}